package com.atguigu.day03;

import com.atguigu.utils.IntegerSource;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

// 整数数据源的平均值
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .map(r -> Tuple2.of(r, 1))
                .returns(Types.TUPLE(Types.INT, Types.INT))
                // 为所有的数据都指定key为1
                // 将所有的数据都发送到同一个逻辑分区
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(
                                value1.f0 + value2.f0, // 所有数据的总和
                                value1.f1 + value2.f1  // 一共多少条数据的统计
                        );
                    }
                })
                .map(r -> r.f0 / r.f1)
                .print();

        env.execute();
    }
}
